package com.maple.file.service.impl;

import com.maple.file.service.IFileUploadService;
import com.maple.file.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
@Slf4j
public class LocalServiceImpl extends AbstractFileUploadServiceImpl implements IFileUploadService {

    @Value("${file.upload.savePath}")
    private String savePath;

    @Value("${file.upload.host}")
    private String readPath;

    @Value("${spring.profiles.active}")
    private String profilesActive;

    @Override
    public String uploadFile(MultipartFile file, String originalName) {
        try {
            String fileName = UUID.randomUUID().toString() + originalName.substring(originalName.lastIndexOf("."));
            String prefix = "/maple/upload";
            // 开发环境 上传本地
            String filePath = "";
            if (profilesActive.contains("dev")) {
                filePath += "E:/mywork";
            }

            filePath += prefix  + "/";
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);

            log.info("filePath:" + filePath);

            return readPath + prefix + "/" + fileName;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public boolean filterService(String channel) {
        return "local".equals(channel);
    }

    @Override
    public String uploadFileByBytes(byte[] bytes, String fileName, Long userTableId, Long contentLength, String suffix, Boolean isSecret) {
        try {
            String prefix = profilesActive + "/service/" + userTableId;
            FileUtil.uploadFile(bytes, savePath + "/" + prefix + "/", fileName);
            return readPath + "/" + prefix + "/" + fileName;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
